package com.nchu.chatserver.service;


import com.nchu.chatserver.dao.MessageDTO;
import com.nchu.chatserver.entity.User;
import com.nchu.chatserver.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class TcpServer implements Runnable {
    private final Map<Long, Socket> onlineUsers = new ConcurrentHashMap<>(); // 在线用户表

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserService userService;
    private boolean running = false;
    private ServerSocket serverSocket;
    private ExecutorService executorService = Executors.newCachedThreadPool(); // 线程池用于处理客户端连接

    @PostConstruct
    public void startServer() {
        running = true;
        new Thread(this).start();
    }

    public void stopServer() {
        running = false;
        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        executorService.shutdownNow(); // 关闭线程池
    }

    @Override
    public void run() {
        try {
            serverSocket = new ServerSocket(7777);
            System.out.println("TCP Server is running and listening on port 7777...");

            while (running) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Received a connection from " + clientSocket.getInetAddress().getHostAddress());
                executorService.execute(new ClientHandler(clientSocket));
            }
        } catch (Exception e) {
            if (running) {
                e.printStackTrace();
            }
        } finally {
            stopServer();
        }
    }

    // 客户端处理器
    private class ClientHandler implements Runnable {
        private Socket clientSocket;

        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }

        @Override
        public void run() {
            Boolean status;
            int userId = 0;
            String ip = null;
            try {
                ////
                userId = 1;
                ip = null;
                status = true;
                Pattern pattern = Pattern.compile("userId=(\\d+)\\s+ip=(\\d+\\.\\d+\\.\\d+\\.\\d+)");
                ////
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

                // 设置心跳检测
                clientSocket.setKeepAlive(true);

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Received message: " + inputLine);
                    out.println("Hello from TCP Server!");
                    if (inputLine.startsWith("{")) {
                        handleMessage(clientSocket, inputLine);
                    } else {
                        ////
                        Matcher matcher = pattern.matcher(inputLine);
                        if (matcher.find()) {
                            userId = Integer.parseInt(matcher.group(1)); // 提取userId
                            ip = matcher.group(2); // 提取ip
                        }
                        User updateuser = userService.getById(userId);
                        updateuser.setIp(ip);
                        updateuser.setIsOnline(status);
                        userService.updateById(updateuser);
                        // 将用户添加到在线用户表
                        onlineUsers.put((long) userId, clientSocket);
//
                    }


                }
                ////当readLine返回null时，表示客户端关闭了连接
                String address_ip = clientSocket.getInetAddress().getHostAddress();

                status = false;
                User updateuser = userService.getById(userId);
                updateuser.setIp(ip);
                updateuser.setIsOnline(status);
                userService.updateById(updateuser);
                onlineUsers.remove((long) userId);
                ////
                System.out.println("Client disconnected: " + clientSocket.getInetAddress().getHostAddress());
                // 假设我们通过某种方式知道用户的ID
            } catch (Exception e) {

                System.out.println("Connection lost with client: " + clientSocket.getInetAddress().getHostAddress());
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void handleMessage(Socket clientSocket, String message) {
        // 使用正则表达式提取JSON字段
        Map<String, String> jsonFields = extractJsonFields(message);

        try {

                MessageDTO msg = new MessageDTO();

                msg.setSenderId(Integer.parseInt(jsonFields.get("senderId")));
                msg.setReceiverId(Integer.parseInt(jsonFields.get("receiverId")));
                msg.setContent(jsonFields.get("content"));
                msg.setCreateTime(LocalDateTime.now()); // 自动设置当前时间
                messageService.sendMessage(msg);
                // 转发给接收者
                Socket receiver = onlineUsers.get(msg.getReceiverId());
                if (receiver != null) {
                    new PrintWriter(receiver.getOutputStream(), true).println(message);
                }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Map<String, String> extractJsonFields(String json) {
        Map<String, String> fields = new HashMap<>();
    // 修正的正则表达式，能够正确匹配字符串和数值类型
    Pattern pattern = Pattern.compile("\"(\\w+)\":\\s*([\"{]?)([^\"},]+)([\"}]?)");
        Matcher matcher = pattern.matcher(json);

        while (matcher.find()) {
        String key = matcher.group(1);
        String value = matcher.group(3).trim();

        // 去除可能存在的引号
        if (value.startsWith("\"") && value.endsWith("\"")) {
            value = value.substring(1, value.length() - 1);
        }

        fields.put(key, value);
        }

        return fields;
    }
}
